package com.hczt.xhminiapp.adminapi.modules.system.service;

import com.hczt.xhminiapp.db.entity.SysPermission;
import com.hczt.xhminiapp.db.repository.SysPermissionRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 红创-马海强
 * @date 2019-03-13 14:10
 * @description 系统菜单操作类
 */
@Service
public class SysPermissionService {
    
    @Resource
    private SysPermissionRepository sysPermissionRepository;
    
    public List<SysPermission> findSysMenuTree() {
        List<SysPermission> menus = sysPermissionRepository.findAll();
        return menuListToTree(null, menus);
    }

    public List<SysPermission> menuListToTree(SysPermission parent, List<SysPermission> menus) {
        String parentId = parent != null ? parent.getPermissionId() : "0";
        List<SysPermission> children = menus.stream().filter(m -> m.getParentId().equals(parentId)).collect(Collectors.toList());
        if (parent != null) {
            parent.setChildren(children);
        }
        children.forEach(c -> menuListToTree(c, menus));
        return children;
    }

    public List<SysPermission> findAllEnableSysMenuList(){
        return sysPermissionRepository.findByEnabledTrueOrderBySortAsc();
    }

    public SysPermission findSysMenuDetail(String permissionId){
        return sysPermissionRepository.findById(permissionId).get();
    }

    public void update(SysPermission sysPermission){
        sysPermission.setCreateTime(new Date());
        sysPermissionRepository.save(sysPermission);
    }

    public void remove(String permissionId){
        sysPermissionRepository.deleteById(permissionId);
    }

}
